/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import com.codemagi.util.Utils;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/**
 * Redirects incoming requests to a domain of the user's choosing. For example, a request for: 
 * 
 * https://dev1.codemagi.com/some/page.html
 *
 * Could be redirected to: 
 * 
 * https://dev12.codemagi.com/some/page.html
 *
 * @version 1.0
 * @author August Detlefsen for CodeMagi, Inc.
 */
public final class DomainRedirectFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());

    private String targetDomain = "";

    private FilterConfig config = null;

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;

	targetDomain   = config.getInitParameter("targetDomain");
	if (Utils.isEmpty(targetDomain)) 
	    throw new ServletException("Unable to instantiate DomainRedirectFilter: targetDomain not specified");
	
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	HttpServletRequest request = (HttpServletRequest)req;

	//determine the domain by which this request was called
	StringBuffer requestUrl    = request.getRequestURL();
	String requestDomain       = requestUrl.substring(requestUrl.indexOf("//") +2, requestUrl.indexOf("/", requestUrl.indexOf("//") +2));

	log.debug("DomainRedirectFilter REQUEST DOMAIN: " + requestDomain );
	log.debug("                      TARGET DOMAIN: " + targetDomain );

	if ( !targetDomain.equalsIgnoreCase( requestDomain ) ) {

	    String requestProtocol = requestUrl.substring(0, requestUrl.indexOf("//") +2);
	    String requestUri      = request.getRequestURI();

	    String redirectUrl     = requestProtocol + targetDomain + requestUri;
	    log.debug("                       REDIRECT URL: " + redirectUrl);

	    ((HttpServletResponse)response).sendRedirect(redirectUrl);

	} else {
            chain.doFilter(request, response);
        }

	return;
    }

}
